package com.tinyseed.emcp.api.app.aspect;

import com.tinyseed.emcp.api.app.config.DynamicDataSourceContextHolder;
import com.tinyseed.emcp.api.app.config.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;

@Aspect
@Component
@Slf4j
public class DynamicDataSourceAspect {



    @Before("@annotation(targetDataSource))")
    public void switchDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource){
        String name =  targetDataSource.value().getName();
       if ( !DynamicDataSourceContextHolder.containDataSourceKey(name) ) {
            log.error("DataSource [{}] doesn't exist, use default DataSource [{}]", targetDataSource.value());
        } else {

            DynamicDataSourceContextHolder.setDataSourceKey( targetDataSource.value().getName() );
            log.info("Switch DataSource to [{}] in Method [{}]", DynamicDataSourceContextHolder.getDataSourceKey(), joinPoint.getSignature());
        }

    }

    @After("@annotation(targetDataSource))")
    public void restoreDataSource(JoinPoint joinPoint,TargetDataSource targetDataSource){
        DynamicDataSourceContextHolder.clearDataSourceKey();
        log.info("Restore DataSource to [{}] in Method [{}]",
                DynamicDataSourceContextHolder.getDataSourceKey(), joinPoint.getSignature());
    }

}
